﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using HOPU.OnlineSchool.Application.Teachers.Dtos;
using HOPU.OnlineSchool.Core;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace HOPU.OnlineSchool.Application.Teachers.Services
{
    public class TeacherService:ITeacherService,ITransient
    {

        private readonly IRepository<EduTeacher> _teacherService;

        public TeacherService(IRepository<EduTeacher> teacherService)
        {
            _teacherService = teacherService;
        }

        public async Task AddAsync(TeacherAddInput input)
        {
            var model = input.Adapt<EduTeacher>();

            //通过雪花算法生成主键id
            model.Id = YitIdHelper.NextId().ToString();
            await _teacherService.InsertAsync(model);
        }

        public async Task DeleteAsync(string id)
        {
            var model = await _teacherService.FirstOrDefaultAsync(e=>e.IsDeleted==0&&e.Id==id);
            if (model==null) 
                throw Oops.Oh("您已删除或者用户不存在");
            model.IsDeleted = 1;
            model.GmtModified = DateTime.Now;
            //更新指定的字段信息
            await _teacherService.UpdateIncludeAsync(model, new string[] { nameof(model.IsDeleted), nameof(model.GmtModified) });
        }

        public async Task<PagedList<TeacherListOutput>> GetListAsync(int page, int limit, TeacherListInput input)
        {
            var query = _teacherService.Where(t => t.IsDeleted == 0);
            if (!string.IsNullOrWhiteSpace(input.Name))
                query = query.Where(t => t.Name.Contains(input.Name));
            if (input.Level > 0)
                query = query.Where(t => t.Level == input.Level);
            if (input.Begin.HasValue)
                query = query.Where(t => t.GmtCreate >= input.Begin.Value);
            if (input.End.HasValue)
                query = query.Where(t => t.GmtCreate <= input.End.Value);

            var list = await query.OrderByDescending(e => e.GmtCreate).ToPagedListAsync(page, limit);
            return list.Adapt<PagedList<TeacherListOutput>>();
        }

        public async Task<TeacherDto> GetTeacherAsync(string id)
        {
            var model = await _teacherService.FirstOrDefaultAsync(e=>e.IsDeleted==0&&e.Id==id);
            if (model==null)
                throw Oops.Oh("该讲师不存在");
            return model.Adapt<TeacherDto>();
        }

        public async Task UpdateAsync(string id, TeacherDto dto)
        {
            var exists = await _teacherService.AnyAsync(e => e.Id == id && e.IsDeleted == 0);
            if (!exists)
                throw Oops.Oh("该讲师未找到");
            var teacher = dto.Adapt<EduTeacher>();
            await teacher.UpdateExcludeAsync(new[] { nameof(teacher.GmtCreate), nameof(teacher.IsDeleted) });
        }
    }
}
